// pages/orderSure/orderSure.js
import { unified_order, unified_order_v4} from '../../utils/api.js'
import {MD5} from '../../utils/MD5.js'

var haveTap = 1;  // 1: 可以点击 0：不可点击
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    noaddress: false,
    addr: {},
    isinit: true,
    noJian: true,
    count: 0,
    number: 0,
    sumprice: 0,
    goodsSum: 0,
    select_all: false,
    middlearr: [],
    allLists: [],
    allgoodsLists: [],
    goodsId: [],
    mount: [],
    getchecked: "",
    backType: "",
    mg_id:[],
    jifenInput:"",
    integral_arr:[],
    sumintegral:0.00,
    sumprice_old:0.00,
    authSettingUser_task:true,
    total_freight_free:0,
    old_total_freight_free:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    haveTap = 1
    var that = this;
    if (options.select_mgid != undefined){
      var select_mgid = options.select_mgid;
      var params3 = {
        select_mgid: select_mgid,
        uid: app.globalData.userInfo.id
      };
      that.setData({

        backType: 'buycar'
      })
    }else{
      var goodsId = options.goodsId;
      var mount = options.mount;
      var spec_price_id = options.spec_price_id;

      that.setData({
        goodsId: goodsId,
        mount: mount,
        spec_price_id: spec_price_id,
        backType: options.backType
      })
      var params3 = {
        goods_ids: goodsId,
        mount: mount,
        spec_price_id: spec_price_id,
        uid: app.globalData.userInfo.id
      };
    }

    that.getAddressList();
    var url3 = '/order/confirm';

    app.HttpPostSend(url3, params3, function(res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var lists = [];
        var mguids = [];
        var mgids = [];
        var goodsids_str = '';
        var mount_str = '';
        var spec_price_id_str = '';
        var total_freight_free = 0;
        for (let i in res.data.lists) {

          mguids.push(res.data.lists[i].uid);
          mgids.push(res.data.lists[i].mg_id);
          total_freight_free = parseFloat(total_freight_free) + parseFloat(res.data.lists[i].freight_free)
          var obj = {};
          obj = res.data.lists[i];
          var goods_list = res.data.lists[i].goods_list;
          var goodsSum = 0;

          for (let j = 0; j < goods_list.length; j++) {
            goods_list[j].title = goods_list[j].title.slice(0, 18) ;
            goodsSum += goods_list[j].num * goods_list[j].price;
            goodsids_str = goodsids_str + ',' + goods_list[j].id;
            mount_str = mount_str + ',' + goods_list[j].num;
            spec_price_id_str = spec_price_id_str + ',' + goods_list[j].spec_price_id;
          
            
          }
          obj.goodsSum = goodsSum;
          if (res.data.lists[i].only_pick>0){
            res.data.lists[i].is_pick_up = 1;
          }
          obj.limit_orderintegral = res.data.lists[i].limit_orderintegral;
          obj.limit_orderintegralnum = res.data.lists[i].limit_orderintegralnum;
          lists.push(obj);
        }
      
        if (options.select_mgid>0){
          that.setData({
            goodsId: goodsids_str.substring(1),
            mount: mount_str.substring(1),
            spec_price_id: spec_price_id_str.substring(1),
          })
        }
        that.setData({
          mguids: mguids,
          mgids: mgids
        })
        var sumprice = 0;
        var sumprice_goods = 0;
      
        for (let i = 0; i < lists.length; i++) {
          sumprice = sumprice + lists[i].goodsSum;
          
        }
        sumprice_goods = sumprice;
        that.setData({
          allLists: lists,
          sumprice: sumprice.toFixed(2),
          sumprice_old: sumprice.toFixed(2),
          sumprice_goods: sumprice_goods.toFixed(2),
          integral_worth: res.data.integral_worth,
          total_freight_free: total_freight_free,
          old_total_freight_free: total_freight_free,
          user_integral:res.data.user_integral
        })
        // wx:wx.showModal({
        //   title: '友情提示',
        //   content: '您当前有' + res.data.user_integral +'个积分，部分商品可抵扣的金额，请合理使用',
        //   showCancel: false,

        //   success: function(res) {},
        //   fail: function(res) {},
        //   complete: function(res) {},
        // })
      }
    });
  },
  to_login: function () {
    this.setData({
      authSettingUser_task: true,
    });
    wx.navigateTo({
      url: '/shopPages/login/login',
    })
  },
  hiden_task: function () {

    this.setData({
      authSettingUser_task: true,
    });
  },
  choose_delivery:function(e){
    var indx = e.currentTarget.dataset.idx;
    var val = e.currentTarget.dataset.value;
    var only_pick = e.currentTarget.dataset.only_pick;
    if (only_pick>0){
      wx.showModal({
        title: '提示',
        content: '当前商户只支持自提',
        showCancel: false,
        success: function () { }
      })
      return false;
    }
    var str = "allLists[" + indx +"].is_pick_up";
    var sumprice = this.data.sumprice;
    var old_total_freight_free = this.data.old_total_freight_free;
    if(val>0){
      this.setData({
        [str]: 1,
        total_freight_free:0,
      });
    }else{
      this.setData({
        [str]: 0,
        total_freight_free:old_total_freight_free,
      });
    }

  },
  //获取地址信息
  getAddressList:function(){
    var that = this;
    var url2 = '/address/index';
    var params2 = {
      uid: app.globalData.userInfo.id
    };
    app.HttpGetSend(url2, params2, function (res) {
      if (res.msg != "success") {
        app.showTipMsg(res.msg);
      } else {
        var addresslist = res.data.list;
        if (res.data) {
          if (addresslist.length > 0) {
            var addr = addresslist[0];
            var getchecked = addresslist[0].id;
            console.log('that.data.addrinfo');
            console.log(that.data.addrinfo);
            if (!!that.data.addrinfo) {
              console.log(999);
              addr = JSON.parse(that.data.addrinfo);
              getchecked = addr.id;
            }
            that.setData({
              addr: addr,
              getchecked: getchecked,
              noaddress: false
            })
          } else {
            that.setData({
              addr: [],
              getchecked: getchecked,
              noaddress: true
            })
          }
        } else {
          that.setData({
            addr: [],
            getchecked: '',
            noaddress: true
          })
        }
      }
    });
  },
  bindAddTap: function(e) {
    wx.navigateTo({
      url: '../addAddress/addAddress?goodsId=' + this.data.goodsId + '&mount=' + this.data.mount + '&backType=' + this.data.backType + '&spec_price_id=' + this.data.spec_price_id,
    })
  },
  bindEditTap: function(e) {
    wx.navigateTo({
      url: '../myAddress/myAddress?goodsId=' + this.data.goodsId + '&mount=' + this.data.mount + '&getchecked=' + this.data.getchecked + '&backType=' + this.data.backType + '&spec_price_id=' + this.data.spec_price_id,
    })
  },
  //点击名片进入名片首页
  bindCardTap: function(e) {
    var id = e.currentTarget.id;
    wx.switchTab({
      url: '../home/home?id=' + id,
    })
  },
  //点击提交订单
  submitOrder: function(e) {
    
    var that = this;
    if (app.globalData.authSettingUser>0){
      var mgid = e.currentTarget.dataset.mgid;

      if (haveTap == 0) {
        console.log('屏蔽重复点击')
      } else {
        haveTap = 0
        if (that.data.backType == 'buycar') {
          var type = 2;
        } else {
          type = 1;
        }
        var integral_arr = that.data.integral_arr;
        var integral_number = 0;
        for (var ii in integral_arr) {
          if (parseFloat(integral_arr[ii].max_integral) < parseFloat(integral_arr[ii].integral_price)) {
            // console.log(111);
            wx.showToast({
              title: '最多抵扣' + integral_arr[ii].max_integral + '分',
              icon: 'none',
              duration: 1000
            })
            app.showTipMsg();
            haveTap = 1;
            return false;

          }
          var a = /^[0-9]*(\.[0-9]{1,2})?$/;
          if (!a.test(integral_arr[ii].integral_price)) {
            // app.showTipMsg('数值不正确');
            wx.showModal({
              title: '提示',
              content: '数值‘' + integral_arr[ii].integral_price + '’不正确',
              showCancel: false,
              success: function () { }
            })
            haveTap = 1;
            return false;
          }
          if (parseFloat(integral_arr[ii].integral_price) > 0) {
            integral_number += 1;
          }

        }
        var is_all_pick_up = 1;
        var pick_up = [];
        for (var ii in that.data.allLists) {
          var is_pick = that.data.allLists[ii].is_pick_up;
          is_pick = is_pick > 0 ? 1 : 0;
          if (that.data.allLists[ii].limit_orderintegral > 0) {
            if (parseInt(that.data.allLists[ii].limit_orderintegralnum) < parseInt(integral_number)) {
              wx.showModal({
                title: '提示',
                content: '当前商户允许' + that.data.allLists[ii].limit_orderintegralnum + '件商品使用积分',
                showCancel: false,
                success: function () { }
              })
              haveTap = 1;
              return false;
            }
          }
          pick_up.push({ mg_id: that.data.allLists[ii].mg_id, pick_up: is_pick });
          if ((that.data.allLists[ii].is_pick_up == undefined || that.data.allLists[ii].is_pick_up == 0) && is_all_pick_up > 0) {
            is_all_pick_up = 0;
          }
        }

        if (!that.data.addr.id && is_all_pick_up == 0) {
          wx.showToast({
            title: '请先选择地址!',
            icon: 'none',
            duration: 1000
          })
          haveTap = 1;

        } else {
          // console.log('测试有没有userid111：', app.globalData.userInfo.id);
          if (!app.globalData.userInfo.id) {
            wx.showToast({
              title: '清除缓存后重试!',
              icon: 'none',
              duration: 1000
            })
            return false;
          }

          // var url = '/order/add_v2';
          var url = '/order/add_v4';
          var params = {
            is_pick_up: pick_up,
            goods_id: that.data.goodsId,
            mount: that.data.mount,
            spec_price_id: that.data.spec_price_id,
            uid: app.globalData.userInfo.id,
            price: that.data.sumprice,
            address_id: that.data.addr.id,
            mg_uid: app.globalData.SwitchTabParams.v_id,
            type: type,
            integral_arr: integral_arr,
            invite_id: !!app.globalData.shareOptions.share_id ? app.globalData.shareOptions.share_id : app.globalData.shareOptions.invite_id,
            invite_uid: !!app.globalData.shareOptions.carte_id ? app.globalData.shareOptions.carte_id : '',
            timestamp: new Date().getTime(),
          };
          params.sign = app.getSign(params)
          // console.log(params);
          // return false;
          wx.showLoading({
            title: '支付中',
          })
          app.HttpPostSend(url, params, function (res) {
            if (res.msg != "success") {
              // app.showTipMsg(res.msg);
              wx.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: function () { }
              })
              haveTap = 1;
              wx.hideLoading();
            } else {
              console.log(res, app.globalData)

              // 雷达添加查看记录 -提交商品订单数
              var mguids = that.data.mguids;
              var mgids = that.data.mgids;
              for (var ii in mguids) {
                app.radarAdd(mguids[ii], 18, '', '', app.globalData.userInfo.logo)
                app.addlog(mguids[ii],'', app.globalData.userInfo.id, app.globalData.userInfo.username,app.globalData.userInfo.logo, 18, '')
              }


              // 发送模板消息-访客到访通知
              // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '购买商品付款中', '', '', '')

              let params2 = {
                // total_fee: that.data.sumprice * 100,
                openid: app.globalData.openid,
                order_id: res.data,
                body: that.data.title,
                type: 1,
                order_source: 0,
                timestamp: new Date().getTime(),
              }
              params2.sign = app.getSign(params2)
              app.HttpPostSend(unified_order_v4, params2, function (unified_order_res) {
                console.log(unified_order_res)
                if (unified_order_res.msg != "success") {
                  wx.showModal({
                    title: '提示',
                    content: unified_order_res.msg,
                    showCancel: false,
                    success: function () {
                      wx.switchTab({
                        url: '/pages/shop/shop',
                      })
                    }
                  })
                  haveTap = 1;
                  wx.hideLoading();
                } else {
                  if (unified_order_res.data.success == 1) {
                    let order_arr = unified_order_res.data.order_arr
                    let signA = "appId=" + order_arr.appid + "&nonceStr=" + order_arr.noncestr + "&package=prepay_id=" + order_arr.prepayid + "&signType=MD5&timeStamp=" + order_arr.timestamp;
                    let signB = signA + "&key=" + unified_order_res.data.key
                    let new_pay_sign = MD5(signB)
                    console.log(new_pay_sign)
                    wx.requestPayment({
                      timeStamp: unified_order_res.data.order_arr.timestamp,
                      nonceStr: unified_order_res.data.order_arr.noncestr,
                      package: 'prepay_id=' + unified_order_res.data.order_arr.prepayid,
                      signType: 'MD5',
                      paySign: new_pay_sign,
                      profit_sharing: 'Y',
                      success(pay_res) {
                        console.log(pay_res)
                        wx.hideLoading();
                        // 雷达添加查看记录 -商品付款成功数
                        for (var ii in mguids) {
                          var showprice = parseFloat(that.data.sumprice) + parseFloat(that.data.total_freight_free);
                          app.radarAdd(mguids[ii], 19, 0, showprice,  app.globalData.userInfo.logo)
                          app.addlog(mguids[ii], '', app.globalData.userInfo.id, app.globalData.userInfo.username,app.globalData.userInfo.logo, 19, '')
                          // 发送模板消息-访客到访通知
                          app.sendTemplateMessage(mguids[ii], 10, '/shopPages/houOrderDetail/houOrderDetail?order_group_id=' + res.data, '', res.data, '', '', mgids[ii]);
                        }


                        // 发送模板消息-访客到访通知
                        // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '付款成功', '', '', '')
                        
                        wx.redirectTo({
                          url: '/shopPages/orderSuccess/orderSuccess?price=' + showprice + '&id=' + res.data + '&integrals=' + JSON.stringify(integral_arr) + '&freight_free=' + that.data.total_freight_free
                        })
                        haveTap = 1;
                      },
                      fail(err_res) {
                        console.log(err_res)
                        wx.redirectTo({
                          url: '/pages/myOrders/myOrders',
                        })
                        haveTap = 1;
                      }
                    })
                  } else {
                    for (var ii in mguids) {
                      var showprice = parseFloat(that.data.sumprice) + parseFloat(that.data.total_freight_free);
                      app.radarAdd(mguids[ii], 19, 0, showprice,  app.globalData.userInfo.logo)
                      // 发送模板消息-访客到访通知
                      app.sendTemplateMessage(mguids[ii], 10, '/shopPages/houOrderDetail/houOrderDetail?order_group_id=' + res.data, '', res.data, '', '', mgids[ii]);
                      app.addlog(mguids[ii], '', app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 19,'')
                    }
                    // 雷达添加查看记录 -商品付款成功数
                    // app.radarAdd(app.globalData.SwitchTabParams.v_id, 19)
                   
                    // 发送模板消息-访客到访通知
                    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 1, '/radarPages/radarCenter/radarCenter', '付款成功', '', '', '')
                    // 发送模板消息-访客到访通知
                    // app.sendTemplateMessage(app.globalData.SwitchTabParams.v_id, 9, '', '', res.data, '', '', mgid);

                    
                    wx.redirectTo({
                      url: '/shopPages/orderSuccess/orderSuccess?price=' + showprice + '&id=' + res.data + '&integrals=' + JSON.stringify(integral_arr) + '&freight_free=' + that.data.total_freight_free
                    })
                    haveTap = 1;
                    wx.hideLoading();
                  }

                }
              })
            }
          });
        }
      }
    }else{
      that.setData({
        authSettingUser_task: false
      });
    }
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log(111);
    if (!!wx.getStorageSync('addrinfo')){
      console.log(333);
      this.setData({
        addrinfo: wx.getStorageSync('addrinfo')
      })
    }else{
      console.log(2131);
      this.setData({
        addrinfo: ''
      })
    }
    this.getAddressList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  integralInput:function(e){
    var that = this;
    var integral = e.detail.value;
    if (integral==''){
      integral = 0;
    }
    
    var sumintegral = 0;
    if (parseFloat(integral) > parseFloat(e.currentTarget.dataset.max)){
      app.showTipMsg('最多抵扣' + e.currentTarget.dataset.max+'分');
      wx.showToast({
        title: '最多抵扣' + e.currentTarget.dataset.max+'分',
        icon: 'none',
        duration: 1000
      })
      // return false;
    }
    var arr = that.data.integral_arr;
    var spec_price_id = e.currentTarget.dataset.spec_price_id;
    var goods_id = e.currentTarget.dataset.goods_id;
    var max = e.currentTarget.dataset.max;
    var search = -1;
    if (arr.length>0){

      for (var i in arr) {

        if (parseInt(arr[i].goods_id) === parseInt(goods_id) && parseInt(arr[i].spec_price_id) === parseInt(spec_price_id)) {
          // console.log(arr[i].goods_id);
          // arr[i].integral_price = integral;
          search = i;

          break;
        } else {
          // console.log('哈哈');
          // arr.push({ goods_id: goods_id, integral_price: integral, max_integral: max });
        }
      }
      if (search>=0){
        arr[i].integral_price = integral;
      }else{
        arr.push({ goods_id: goods_id, integral_price: integral, max_integral: max, spec_price_id: spec_price_id});
      }
      // sumintegral = (parseFloat(sumintegral) + parseFloat(integral)).toFixed(2);

    }else{
      arr.push({ goods_id: goods_id, integral_price: integral, max_integral: max, spec_price_id: spec_price_id});
      // console.log(arr);
      // sumintegral = (parseFloat(sumintegral) + parseFloat(integral)).toFixed(2);
    }

    for (var i in arr) {
      // console.log(arr[i].integral);
      sumintegral = (parseFloat(sumintegral) + parseFloat(arr[i].integral_price)).toFixed(2);
    }


    if (sumintegral==NaN){
      sumintegral=  0;
    }
    var integral_worth = that.data.integral_worth;
    var dec = (sumintegral / integral_worth).toFixed(2);
    var sumprice = that.data.sumprice_old;
    sumprice = (parseFloat(sumprice) - parseFloat(dec)).toFixed(2);
    if (sumprice<0){
      sumprice = 0;
    }
    that.setData({
      sumintegral: sumintegral,
      sumprice: sumprice
    });


  }

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
})